from sqlalchemy.sql.schema import Column
from sqlalchemy.sql.sqltypes import Boolean, Integer, String, Text, DateTime
from sqlalchemy.sql.functions import func
from sqlalchemy.orm import relationship

from app.core.database import Base


class Role(Base):
    """角色模型 - RBAC中的Role"""
    __tablename__ = "roles"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), unique=True, index=True, nullable=False)
    display_name = Column(String(100), nullable=False)
    description = Column(Text)
    
    # 角色级别 (1-10, 数字越大权限越高)
    level = Column(Integer, default=1, nullable=False)
    
    # 状态字段
    is_active = Column(Boolean, default=True, nullable=False)
    is_system = Column(Boolean, default=False, nullable=False)  # 系统内置角色
    
    # 审计字段
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联关系
    role_permissions = relationship("RolePermission", back_populates="role", cascade="all, delete-orphan")
    user_roles = relationship("UserRole", back_populates="role", cascade="all, delete-orphan")
    permissions = relationship("Permission", secondary="role_permissions", back_populates="roles", overlaps="role_permissions")
    users = relationship("User", secondary="user_roles", back_populates="roles", overlaps="user_roles")
    
    def __repr__(self):
        return f"<Role(id={self.id}, name='{self.name}', display_name='{self.display_name}')>"
    
    def get_permission_names(self):
        """获取角色的所有权限名称"""
        return [permission.name for permission in self.permissions if permission.is_active]
    
    def has_permission(self, permission_name: str) -> bool:
        """检查角色是否具有特定权限"""
        return any(
            permission.name == permission_name and permission.is_active
            for permission in self.permissions
        )